import pygame

from jeo.gameobject import GameObject
from jeo.constants import *

class BoxDir:
    X_STOP = "x stop"
    X_LEFT = "x left"
    X_RIGHT = "x right"


class Box(GameObject):
    def __init__(self, gameworld=None):
        super().__init__(gameworld)
        self.color = "green"
        self.image.fill(self.color)

        self.rect.bottom = self.gameworld.height
        self.rect.centerx = self.gameworld.width / 2

        self.vx = 5
        self.jump_vy = 20
        self.vy = self.jump_vy
        self.gravity = GRAVITY
        self.jump_air = 2

        self.dir_x = BoxDir.X_STOP

        self.can_jump = True

    def update(self, events):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key in [pygame.K_UP, pygame.K_SPACE, pygame.K_w] \
                        and self.can_jump == True:
                    self.jump()
                if event.key in [pygame.K_LEFT, pygame.K_a]:
                    self.dir_x = BoxDir.X_LEFT
                if event.key in [pygame.K_RIGHT, pygame.K_d]:
                    self.dir_x = BoxDir.X_RIGHT
            if event.type == pygame.KEYUP:
                if event.key in [pygame.K_LEFT, pygame.K_a, pygame.K_RIGHT, pygame.K_d]:
                    self.dir_x = BoxDir.X_STOP


        if self.dir_x == BoxDir.X_LEFT:
            self.rect.x -= self.vx
        if self.dir_x == BoxDir.X_RIGHT:
            self.rect.x += self.vx

        self.rect.y -= self.vy
        self.vy += self.gravity

        # bricks detection
        brick_list = pygame.sprite.spritecollide(self, self.gameworld.bricks, False)
        if len(brick_list)>0:
            brick = brick_list[0]
            # hit the brick
            if self.vy <= 0:
                # 落下
                # print("落上平台")
                self.rect.bottom = brick.rect.top
                self.vy = 0
                self.can_jump = True
                self.jump_air = 2
            else:
                # 顶上平台
                # print("碰头")
                self.vy = -self.vy

        # ground detection
        if self.rect.bottom > self.gameworld.height:
            self.rect.bottom = self.gameworld.height
            self.can_jump = True
            self.jump_air = 2
            self.vy = 0

    def jump(self):
        self.vy = self.jump_vy
        self.jump_air -= 1
        if self.jump_air <= 0:
            self.can_jump = False
